package cn.com.headfree.job;

import java.util.Date;

import org.quartz.Job;
import org.quartz.JobDataMap;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.client.RestTemplate;

import com.gta.edu.sdk.common.dto.ResultData;
import com.gta.edu.sdk.util.RedisClusterUtil;

import cn.com.headfree.entity.TCommonTaskExecuteRecord;

public class CommonJob implements Job {
	private static final Logger log = LoggerFactory.getLogger(CommonJob.class);
	private RestTemplate template;
	private static final int REDIS_TASK_TIMEOUT = 300;

	@Override
	public void execute(JobExecutionContext context) throws JobExecutionException {
		JobDataMap jdm = context.getJobDetail().getJobDataMap();
		String jobCode = jdm.getString("jobCode");
		boolean result = RedisClusterUtil.getInstance().setIfAbsent("common-task-" + jobCode, jobCode, REDIS_TASK_TIMEOUT);
		if (result) {
			TCommonTaskExecuteRecord record = new TCommonTaskExecuteRecord();
			record.setTaskCode(jobCode);
			record.setExecuteTime(new Date());
			try {
//				log.info("我获取了锁，开始执行任务!");
				Object obj = jdm.get("template");
				this.template = (RestTemplate) obj;
				ResultData resultData = this.template.getForObject(jdm.getString("proceedMethod"), ResultData.class);
				if (resultData.isSuccess()) {
					record.setExecuteResult(1);
//					log.info("任务执行完成，任务编码是:" + jobCode);
				} else {
					record.setExecuteResult(0);
					record.setExecuteErrorMessage("失败原因：" + resultData.getErrorMsg());
//					log.info("任务执行失败，任务编码是:" + jobCode + "，失败原因：" + resultData.getErrorMsg());
				}
			} catch (Exception e) {
				log.error("定时任务【" + jobCode + "】执行出现了异常！", e);
				record.setExecuteResult(2);
				record.setExecuteErrorMessage("异常信息：" + e.getMessage());
			} finally {
				RedisClusterUtil.getInstance().stringExpire("common-task-" + jobCode, 1);
				CommonScanJob.recordList.add(record);
			}
		} else {
//			log.info("我未获取了锁，开始执行任务");
		}

	}
}
